// Modified from Vscode
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/

export function $(description, attrs, ...children) {
  const match = SELECTOR_REGEX.exec(description)

  if (!match) {
    throw new Error('Bad use of emmet')
  }

  const tagName = match[1] || 'div'
  const result = document.createElement(tagName)

  if (match[3]) {
    result.id = match[3]
  }
  if (match[4]) {
    result.className = match[4].replace(/\./g, ' ').trim()
  }

  if (attrs) {
    Object.entries(attrs).forEach(([name, value]) => {
      if (typeof value === 'undefined') {
        return
      }

      if (/^on\w+$/.test(name)) {
        result[name] = value
      } else if (name === 'selected') {
        if (value) {
          result.setAttribute(name, 'true')
        }
      } else {
        result.setAttribute(name, value)
      }
    })
  }

  result.append(...children)

  return result
}
